package main

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	"github.com/satori/go.uuid"
	"go.uber.org/zap"
	"mxshop_api/user-web/global"
	"mxshop_api/user-web/initialize"
	"mxshop_api/user-web/utils/register"
	myvalidator "mxshop_api/user-web/validator"
	"os"
	"os/signal"
	"syscall"
)

func main(){
	initialize.InitLogger()
	Router :=initialize.Routers()
	initialize.InitConfig()
	initialize.InitSrvConn()
	if err :=initialize.InitTrans("zh");err !=nil{
		panic(err)
	}
	zap.S().Debug("启动服务器，端口：",global.ServerConfig.Port)



	// 注册验证器
	if v,ok :=binding.Validator.Engine().(*validator.Validate);ok{
		_ = v.RegisterValidation("mobile",myvalidator.ValidateMobile)
		_ = v.RegisterTranslation("mobile",global.Trans, func(ut ut.Translator) error {
			return ut.Add("mobile","{0} 非法的手机号码",true)
		},func(ut ut.Translator,fe validator.FieldError)string{
			t,_ :=ut.T("mobile",fe.Field())
			return t
		})
	}//注册验证器结束

	//服务注册
	register_client :=register.NewRegistryClient("192.168.178.120",8500)
	serviceId :=fmt.Sprintf("%s",uuid.NewV4)
	err :=register_client.Register(global.ServerConfig.Host,global.ServerConfig.Port,global.ServerConfig.Name,serviceId)
	if err != nil {
		zap.S().Panic("服务注册失败",err.Error())
	}


	err =Router.Run(fmt.Sprintf(":%d",global.ServerConfig.Port))
	if err != nil {
		zap.S().Panic("启动失败，",err.Error())
	}
	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = register_client.DeRegister(serviceId); err != nil {
		zap.S().Info("注销失败:", err.Error())
	}else{
		zap.S().Info("注销成功:")
	}
}
